package www.sharetime.weshare.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import www.sharetime.weshare.R;
import www.sharetime.weshare.base.BaseOhterActivity;
import www.sharetime.weshare.event.AddTagEvent;
import www.sharetime.weshare.event.BrandEvent;
import www.sharetime.weshare.event.DeleteTagGroupEvent;
import www.sharetime.weshare.event.GoodsEvent;
import www.sharetime.weshare.response.BrandSearchResponse;
import www.sharetime.weshare.tag.DIRECTION;
import www.sharetime.weshare.tag.model.TagGroupModel;
import www.sharetime.weshare.utils.L;
import www.sharetime.weshare.utils.UIUtils;
import www.sharetime.weshare.utils.ViewShakeUtil;

/**
 * File Description  : 编辑tag的页面
 *
 * @author : zhanggeng
 * @version : v1.0
 *          **************修订历史*************
 * @email : zhanggengdyx@gmail.com
 * @date : 2017/9/20 14:08
 */

public class AddTagActivity extends BaseOhterActivity {

    @BindView(R.id.tv_brand)
    TextView tvBrand;
    @BindView(R.id.img_del_brand)
    ImageView imgDelBrand;
    @BindView(R.id.img_del_brand_name)
    ImageView imgDelBrandName;
    @BindView(R.id.tv_brand_name)
    TextView tvBrandName;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.img_del_money)
    ImageView imgDelMoney;
    @BindView(R.id.tv_money_num)
    EditText tvMoneyNum;
    @BindView(R.id.tv_city)
    TextView tvCity;
    @BindView(R.id.img_del_city)
    ImageView imgDelCity;
    @BindView(R.id.edt_city_input)
    TextView edtCityInput;
    @BindView(R.id.img_del_city_input)
    ImageView imgDelCityInput;
    @BindView(R.id.img_tag_edit_finish)
    ImageView imgTagEditFinish;
    @BindView(R.id.img_tag_edit_cancle)
    ImageView imgTagEditCancle;

    BrandSearchResponse.BrandEntity brandEntity;

    TagGroupModel tagGroupModel;

    //标志位：当前是否处于对标签的编辑模式，false 非编辑；true 编辑； 默认 false；
    private boolean isEditTagState = false;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_tag_edit;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        popTagEditWindow();

        Bundle bundle = getIntent().getExtras();

        if (bundle != null) {
            tagGroupModel = bundle.getParcelable("model");

            isEditTagState = true;

            L.et("isNull", (tagGroupModel != null) + " ");


            //这儿编辑完了，要删除原来的标签
            for (int i = 0; i < tagGroupModel.getTags().size(); i++) {

                L.et("tag", tagGroupModel.getTags().get(i).toString());
                if (tagGroupModel.getTags().get(i).getTagName().equals("brand")) {
                    String[] brands = tagGroupModel.getTags().get(i).getName().split(" ");

                    tvBrand.setText(brands[0]);
                    imgDelBrand.setVisibility(View.VISIBLE);

                    tvBrandName.setText(brands[1]);
                    imgDelBrandName.setVisibility(View.VISIBLE);
                } else if (tagGroupModel.getTags().get(i).getTagName().equals("money")) {

                    String[] moneys = tagGroupModel.getTags().get(i).getName().split(" ");

                    tvMoney.setText(moneys[1]);
                    imgDelMoney.setVisibility(View.VISIBLE);

                    tvMoneyNum.setText(moneys[0]);
                } else if (tagGroupModel.getTags().get(i).getTagName().equals("city")) {

                    edtCityInput.setText(tagGroupModel.getTags().get(i).getName());
                }
            }
        }
    }

    private void popTagEditWindow() {
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay();  //为获取屏幕宽、高
        WindowManager.LayoutParams p = getWindow().getAttributes();  //获取对话框当前的参数值
        p.height = (int) (d.getHeight() * 1.0);   //高度设置为屏幕的1.0
        p.width = (int) (d.getWidth() * 1.0);    //宽度设置为屏幕的0.8
        p.alpha = 0.8f;      //设置本身透明度
        p.dimAmount = 0.6f;      //设置黑暗度
        getWindow().setAttributes(p);
    }

    private void onTagEditFinish() {
        if (!isEditTagState) {
            if (addNewTagGroup())
                return;

        } else {
            //如果处于编辑状态比对内容是否编辑，如果是经过编辑的，那么发送事件，删除原来的标签组，创建新的标签组。
            /**
             * 1. 比对，标签内容是否变化；
             * 2. 如果内容发生变化，发送事件——删除原来的标签，添加新的标签组；
             * 3. 如果内容没有变化，不生成新的标签；
             */

            if (tagContentIsChange()) {

                //先删除原来的标签组
                deleteOldTagGroup();

                //添加新的标签组；
                addNewTagGroup();
            }
        }
        UIUtils.closeActivity(AddTagActivity.this);
    }

    /**
     * 如何来删除？
     */
    private void deleteOldTagGroup() {
       //发送事件删除原来的taggroup
        EventBus.getDefault().post(new DeleteTagGroupEvent(tagGroupModel));
    }

    private boolean addNewTagGroup() {
        //标签添加完毕后，关闭页面
        if (!tvMoneyNum.getText().toString().equals("") && tvMoney.getText().toString().equals("")) {
            ViewShakeUtil.shakeViewWithToast(AddTagActivity.this, tvMoney, "请选择币种");
            return true;
        }
        if (!tvBrandName.getText().equals("")
                || !tvMoneyNum.getText().toString().equals("")
                || !edtCityInput.getText().toString().equals("")) {
            if (createTagGroup() != null) {
                EventBus.getDefault().post(createTagGroup());
            }
        }
        return false;
    }

    /**
     * 比较标签内容，是否发生了变化
     * <p>
     * 1. 标签品牌，商品名；
     * 2. 币种，价格
     * 3. 城市名字
     *
     * @return
     */
    private boolean tagContentIsChange() {
        for (int i = 0; i < tagGroupModel.getTags().size(); i++) {

            if (tagGroupModel.getTags().get(i).getTagName().equals("brand")) {
                String[] brands = tagGroupModel.getTags().get(i).getName().split(" ");

                if (!tvBrand.getText().toString().equals(brands[0]) || !tvBrandName.getText().toString().equals(brands[1])) {
                    //说明发生了变化，要发送事件删除原来的TagGroup
                    return true;
                }

            } else if (tagGroupModel.getTags().get(i).getTagName().equals("money")) {

                String[] moneys = tagGroupModel.getTags().get(i).getName().split(" ");
                //说明发生了变化，要发送事件删除原来的TagGroup
                if (!tvMoney.getText().toString().equals(moneys[1]) || !tvMoneyNum.getText().toString().equals(moneys[0])) {
                    return true;
                }
            } else if (tagGroupModel.getTags().get(i).getTagName().equals("city")) {

                edtCityInput.setText(tagGroupModel.getTags().get(i).getName());
                //说明发生了变化，要发送事件删除原来的TagGroup
                if (!edtCityInput.getText().toString().equals(tagGroupModel.getTags().get(i).getName())) {
                    return true;
                }
            }
        }
        return false;
    }

    public TagGroupModel createTagGroup() {
        TagGroupModel model = new TagGroupModel();
        List<TagGroupModel.Tag> tagList = new ArrayList<>();
        String str01 = tvBrand.getText().toString() + " " + tvBrandName.getText().toString();
        String str02 = tvMoneyNum.getText().toString();
        String str03 = edtCityInput.getText().toString();
        if (!TextUtils.isEmpty(str01) && str01.split(" ").length == 2) {
            TagGroupModel.Tag tag = new TagGroupModel.Tag();
            tag.setName(str01);
            tag.setTagName("brand");
            tagList.add(tag);
        }
        if (!TextUtils.isEmpty(str02)) {
            TagGroupModel.Tag tag = new TagGroupModel.Tag();
            tag.setName(str02 + " " + tvMoney.getText());
            tag.setTagName("money");
            tagList.add(tag);
        }
        if (!TextUtils.isEmpty(str03)) {
            TagGroupModel.Tag tag = new TagGroupModel.Tag();
            tag.setName(str03);
            tag.setTagName("city");
            tagList.add(tag);
        }
        setTagDirection(tagList);
        model.getTags().addAll(tagList);
        model.setPercentX(0.5f);
        model.setPercentY(0.5f);
        return model;
    }

    private void setTagDirection(List<TagGroupModel.Tag> tagList) {
        switch (tagList.size()) {
            case 3:
                tagList.get(0).setDirection(DIRECTION.RIGHT_TOP.getValue());
                tagList.get(1).setDirection(DIRECTION.RIGHT_CENTER.getValue());
                tagList.get(2).setDirection(DIRECTION.RIGHT_BOTTOM.getValue());
                break;
            case 2:
                tagList.get(0).setDirection(DIRECTION.RIGHT_TOP.getValue());
                tagList.get(1).setDirection(DIRECTION.RIGHT_BOTTOM.getValue());
                break;
            case 1:
                tagList.get(0).setDirection(DIRECTION.RIGHT_CENTER.getValue());
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            UIUtils.closeActivity(AddTagActivity.this);
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 获取tag监听
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAddTag(AddTagEvent event) {
        if (event != null) {

            if (event.getFrom().equals(MoneyTypeSearchActivity.class.getSimpleName())) {
                tvMoney.setText(event.getValue());
                imgDelMoney.setVisibility(View.VISIBLE);
            } else if (event.getFrom().equals(CitySearchActivity.class.getSimpleName())) {
                edtCityInput.setText(event.getValue());
                imgDelCityInput.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * 获取品牌事件监听
     *
     * @param brandEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBrandSelect(BrandEvent brandEvent) {
        if (brandEvent != null) {
            brandEntity = brandEvent.getBrandEntity();
            tvBrand.setText(brandEntity.getBrandName());
            imgDelBrand.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 某品牌下的商品
     *
     * @param goodsEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGoodsSelect(GoodsEvent goodsEvent) {
        if (goodsEvent != null && goodsEvent.getGoodsName() != null && !goodsEvent.getGoodsName().equals("")) {

            L.et("goodsEvent", goodsEvent.getGoodsName());
            if (goodsEvent.getGoodsName().contains(" ")) {
                tvBrandName.setText(goodsEvent.getGoodsName().split(" ")[1]);
            } else {
                tvBrandName.setText(goodsEvent.getGoodsName());
            }
            imgDelBrandName.setVisibility(View.VISIBLE);
        }
    }


    @OnClick({R.id.tv_brand, R.id.img_del_brand, R.id.img_del_brand_name, R.id.tv_brand_name, R.id.tv_money, R.id.img_del_money, R.id.tv_city, R.id.img_del_city, R.id.edt_city_input, R.id.img_del_city_input, R.id.img_tag_edit_finish, R.id.img_tag_edit_cancle})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_money:
                //点击后，跳转到币种选择页面
                UIUtils.startActivity(AddTagActivity.this, MoneyTypeSearchActivity.class);
                break;
            case R.id.img_del_money:
                //点击币种选择后面的X号后：清空选择内容，隐藏 X 号
                tvMoney.setText("");
                imgDelMoney.setVisibility(View.INVISIBLE);
                break;
            case R.id.tv_city:
                break;
            case R.id.img_del_city:
                break;
            case R.id.edt_city_input:
                UIUtils.startActivity(AddTagActivity.this, CitySearchActivity.class);
                break;
            case R.id.img_del_city_input:
                //点击清除选中的城市名字，并恢复默认提示
                edtCityInput.setText("");
                imgDelCityInput.setVisibility(View.INVISIBLE);
                break;
            case R.id.tv_brand:
                //商品名字，点击跳转至商品选择页面
                UIUtils.startActivity(AddTagActivity.this, BrandListActivity.class);
                break;
            case R.id.img_del_brand:
                //点击清除商品品牌名字 并恢复默认提示。
                imgDelBrand.setVisibility(View.GONE);
                tvBrand.setText("");
                break;
            case R.id.img_del_brand_name:
                //点击清除选中内容，并恢复默认提示。
                imgDelBrandName.setVisibility(View.GONE);
                tvBrandName.setText("");
                break;
            case R.id.tv_brand_name:
                //点击，跳转到商品选择页面
                jumpToSelectProduct();
                break;
            case R.id.img_tag_edit_finish:
                //点击完成按钮
                onTagEditFinish();
                break;
            case R.id.img_tag_edit_cancle:
                //点击取消按钮
                UIUtils.closeActivity(AddTagActivity.this);
                break;
        }
    }

    /**
     * 跳转到商品选择页面
     */
    private void jumpToSelectProduct() {

        if (tvBrand.getText().equals("")) {
            ViewShakeUtil.shakeViewWithToast(AddTagActivity.this, tvBrand, "请选择品牌");
            return;
        }

        Intent intent = new Intent(AddTagActivity.this, BrandListActivity.class);
        L.et("brandEntity", brandEntity.toString());
        intent.putExtra("id", brandEntity.getId());
        intent.putExtra("name", brandEntity.getBrandName());

        startActivity(intent);
    }
}
